package com.example.opengldemo.vertex_magical;

import android.opengl.EGLSurface;
import android.opengl.GLES30;

import com.example.opengldemo.util.MatrixUtils;
import com.example.opengldemo.vertex_magical.core.FrameObserver;
import com.example.opengldemo.vertex_magical.shader.LazyRenderer;

public class FrameHandle implements FrameObserver<FrameBean> {
    private Object mSurface;
    private EGLSurface mShowSurface;
    private FrameBean mBean;
    private boolean isShow=false;

    private LazyRenderer mFilter;

    private int mMatrixType= MatrixUtils.TYPE_CENTERCROP;

    private int mWidth;
    private int mHeight;
    public void setOutputSize(int width,int height){
        this.mWidth=width;
        this.mHeight=height;
    }


    private OnDrawEndListener mListener;

    public void setSurface(Object surface){
        this.mSurface=surface;
        clearSurface();
    }
    private void clearSurface() {
        if(mShowSurface!=null){
            mBean.egl.destroySurface(mShowSurface);
            mShowSurface = null;
        }
    }
    public void open(){
        isShow=true;
    }
    public void close(){
        isShow=false;
    }

    @Override
    public void onCall(FrameBean rb) {
        if(rb.endFlag){
            clearSurface();
        }else if(isShow&&mSurface!=null){
            if(mShowSurface==null){
                mBean = rb;
                mShowSurface=rb.egl.createWindowSurface(mSurface);

                mFilter=new LazyRenderer();
                mFilter.create();
                mFilter.sizeChanged(rb.sourceWidth, rb.sourceHeight);
                MatrixUtils.getMatrix(
                        mFilter.getVertexMatrix(), mMatrixType,
                        rb.sourceWidth,rb.sourceHeight,
                        mWidth,mHeight);
                MatrixUtils.flip(mFilter.getVertexMatrix(),false,true);

            }
            rb.egl.makeCurrent(mShowSurface);
            GLES30.glViewport(0,0,mWidth,mHeight);
            mFilter.draw(rb.textureId);
            if(mListener!=null){
                mListener.onDrawEnd(mShowSurface,rb);
            }
            rb.egl.swapBuffers(mShowSurface);
        }
    }

    public void setOnDrawEndListener(OnDrawEndListener listener){
        this.mListener=listener;
    }

    public interface OnDrawEndListener{
        void onDrawEnd(EGLSurface surface, FrameBean bean);
    }
}
